//获取某一个cookie的值
export const getCookie = key => {
    let k = key, dc = document.cookie;
    if (dc.length > 0) {
        let s = dc.indexOf(k + "=");
        if (s != -1) {
            s = s + k.length + 1;
            let e = dc.indexOf(";", s);
            (e === -1 && (e = dc.length));
            return unescape(dc.substring(s, e));
        }
    }
    return "";
};

//获取某一个所有cookie的值，并返回对象
export const getAllCookies = () => {
    let arr = unescape(document.cookie).split("; "), o = {};
    for (let i = 0, len = arr.length; i < len; i++) {
        let a = arr[i], index = a.indexOf("="), b = a.substr(0, index), c = a.substr(index + 1);
        o[b] = c;
    }
    return o;
};

//设置某一个cookie的值
export const setCookie = (key, val, seconds = 365 * 24 * 60 * 60, path, domain) => {
    if (val == null || val == undefined) return;
    let k = key, s = seconds, e = new Date();
    e.setSeconds(e.getSeconds() + s);
    val instanceof Array && (val = val.join("||")), val instanceof Object && (val = JSON.stringify(val));
    document.cookie = `${k}=${escape(val.toString())}${s == null ? "" : ";expires=" + e.toUTCString()};path=${path || "/"};domain=${domain || location.hostname}`;
};

//删除某一个cookie的值
export const delCookie = (key, path, domain) => {
    let k = key, val = getCookie(k);
    if (val != null) document.cookie = `${k}=0;expires=${new Date(0).toUTCString()};path=${path || "/"};domain=${domain || location.hostname}`;
};

//删除所有cookie的值
export const delAllCookies = (path, domain) => (document.cookie.match(/[^ =;]+(?=\=)/g) || []).forEach(v => document.cookie = `${v}=0;expires=${new Date(0).toUTCString()};path=${path || "/"};domain=${domain || location.hostname}`);
